<?php
namespace Home\Controller;
class PowerController extends BackController{
    public function index(){
    $menu_data = C('MENU');
        //把二级栏目拿到一级栏目
        foreach($menu_data as $key=>$val) {
							$new_data[$val['id']] = $val['name'];
            foreach($val['son'] as $v) {
              $new_data[$v['id']] = $v['name'];
            }
        }
        //使用D调用模型类
        $power = M('power');
        $data = $power->select();
        foreach($data as $k=>$v) {
            $data1 = json_decode($v['content'],true);
            //声明一个空数组 避免数据的循环累加
            $data2 = array();
            //循环数组根据子栏目id获取栏目对应的名称
            foreach($data1 as $v2) { //11,12,21,31
                $data2[] = $new_data[$v2];
            }
            //把获取到的子栏目放到循环的$data数组里面
            $data[$k]['data_content'] = $data2;
        }
				//var_dump($data);
        $this->assign('data',$data);
        $this->display();
    }
    //添加权限
    public function add(){
        $power = D('Power');
        if(IS_POST){
            $data['title'] = I('post.title','','addslashes');
            $data['content'] = json_encode(I('post.content','','addslashes'));
            if($power->create()){
                if($power->add($data)){
                    $this->success('添加成功',U('Power/index'));
                }else{
                    $this->error('添加失败',U('Power/index'));
                }
            }else{
                $this->error($power->getError());
            }
        }else{
        $menu_data = C('MENU');
        $this->assign('menu_data',$menu_data);
        $this->display();
        }
    }
    //编辑权限
    public function edit(){
        $power = D('Power');
        if(IS_POST){
            $id = I('post.id','','int');
            $data['title'] = I('post.title','','addslashes');
            $data['content'] = json_encode(I('post.content','','addslashes'));
            if($power->create()){
                if($power->where('id='.$id)->save($data) !==false){
                    $this->success('编辑成功',U('Power/index'));
                }else{
                    $this->error('编辑失败',U('Power/index'));
                }
            }else{
                $this->error($power->getError());
            }
        }else{
            //获取要编辑的数据
            $id = I('get.id',0,'int');
            $data = $power->where('id='.$id)->find();
            $data['content'] = json_decode($data['content'],true);
           // print_r($data);
            $this->assign('data',$data);
            //添加角色之前 查询出所有的菜单
            $menu_data = C('MENU');
            $this->assign('menu_data',$menu_data);
            $this->display();
        }
    }
    //删除权限
    public function del(){
        if(IS_AJAX){
            $id = I('post.id','','int');
            $power = M('power');
            if($power->where('id='.$id)->delete()){
                echo 1;
            }else{
                echo 0;   
            }
        }else{
            echo -1;
        }
    }
}
